<template>
	<a-row :gutter="10" class="mb-2" v-if="!props.hiddenFlag">
		<a-col :span="5">
			<Group height="calc(71vh)"  :selectTree="selectTree" relationTypeCode="SCENE" :productId="productId"></Group>
		</a-col>
		<a-col :span="19">

			<a-row :gutter="10" class="mb-2">
				<a-col :span="24">
					<a-card>
						<a-space>
							<a-input-search placeholder="请输入内容" v-model:value="search"
											@search="tableRef.refresh(true)"></a-input-search>
							<a-button type="primary" @click="add">新增</a-button>
						</a-space>
					</a-card>
				</a-col>
			</a-row>

			<a-row :gutter="10" class="mb-2">
				<a-col :span="24">
					<a-card>
						<h-table :columns="columns" height="calc(70vh)" ref="tableRef" :data="queryList">

						</h-table>
					</a-card>
				</a-col>
			</a-row>

		</a-col>
	</a-row>


	<a-modal v-model:open="viewConfig.visibleFlag" :closable="false" width="300px">
		<a-form :model="viewConfig">
			<a-form-item label="编码">
				<a-input :disabled="viewConfig.id != null" v-model:value="viewConfig.viewCode"></a-input>
			</a-form-item>

			<a-form-item label="名称">
				<a-input v-model:value="viewConfig.viewName"></a-input>
			</a-form-item>

			<a-form-item label="简介">
				<a-input v-model:value="viewConfig.description"></a-input>
			</a-form-item>

			<a-form-item label="上级菜单">
				<a-tree-select v-model:value="viewConfig.parentId" v-model:treeExpandedKeys="defaultExpandedKeys"
							   style="width: 100%;"
							   :dropdown-style="{ maxHeight: '400px', overflow: 'auto', zIndex: '99999' }"
							   placeholder="请选择上级菜单" allow-clear tree-default-expand-all :tree-data="treeData"
							   :field-names="{
						children: 'children',
						label: 'title',
						value: 'id'
					}" selectable="false" tree-line/>
			</a-form-item>

			<a-form-item label="路由地址">
				<a-input v-model:value="viewConfig.routeUrl"></a-input>
			</a-form-item>

			<a-form-item label="图标">

				<span v-if="viewConfig.icon != null && fileList.length == 0"
					  style="position: absolute;left:100px;top:-15px;">
					<a-image style="width: 50px; height: 50px" :src="viewConfig.icon"/>
				</span>


				<a-upload ref="upload" v-model:file-list="fileList" :multiple="false" :before-upload="beforeUpload"
						  @change="progress">
					<a-button type="primary">
						<upload-outlined></upload-outlined>
						上传
					</a-button>
					<template #itemRender="{ file, actions }">
						<div style="position: absolute;left: 100px;top:-10px;">
							<a-image style="width: 50px; height: 50px" :src="viewConfig.icon"/>
						</div>
					</template>
				</a-upload>
			</a-form-item>

		</a-form>
		<template #footer>
			<a-space>
				<a-button @click="viewConfig.visibleFlag = false">取 消</a-button>
				<a-button v-if="!viewConfig.viewFlag" type="primary" @click="save">确 定</a-button>
			</a-space>
		</template>

	</a-modal>
</template>

<script setup>
import Group from '@/components/Group/index.vue'
import {onMounted, ref, getCurrentInstance, defineProps, nextTick} from "vue";
import viewConfigApi from '@/api/viewConfig/viewConfigApi.js'
import {useRouter} from "vue-router";
import menuApi from '@/api/sys/resource/menuApi'
import userCenterApi from '@/api/sys/userCenterApi'
import tool from '@/utils/tool'

//["hiddenFlag", "productId", "operaCallback"]
const props = defineProps({
	hiddenFlag:{
		type: Boolean,
		default: false,
	},
	productId:{
		type: String,
		default:""
	},
	operaCallback:{
		type: Function
	}
})
const currentGroupId = ref();
const productId = ref()
// 默认展开的节点(顶级)
const defaultExpandedKeys = ref([0]);

const {proxy} = getCurrentInstance();

const fileList = ref([])
const columns = ref([
	{
		title: '名称',
		key: 'viewName',
		dataIndex: 'viewName',
		ellipsis: true,
	},
	{
		title: '编码',
		key: 'viewCode',
		dataIndex: 'viewCode',
		ellipsis: true,
	},
	{
		title: '描述',
		key: 'description',
		dataIndex: 'description',
		ellipsis: true,
	},
	{
		title: '路由地址',
		key: 'routeUrl',
		dataIndex: 'routeUrl',
		ellipsis: true,
	},
	{
		title: '操作',
		key: 'action',
		dataIndex: 'action',
		ellipsis: true,
		width: 300,
		fixed: 'right',
		buttonList: [
			{

				click: (field, record) => {
					online(record)
				},
				render: (record) => {
					if (record.publishFlag == 'OFFLINE' || !record.publishFlag) {
						return "上线";
					}

				}
			},
			{

				click: (field, record) => {
					offline(record)
				},
				render: (record) => {
					if (record.publishFlag == 'ONLINE') {
						return "下线";
					}
				}
			},
			{
				click: (field, record) => {
					views(record)
				},
				render: (record) => {
					return '查看';
				}
			},
			{
				type: 'primary',
				click: (field, record) => {
					edit(record)
				},
				render: (record) => {
					return "修改";
				}
			},
			{

				click: (field, record) => {
					remove(record)
				},
				render: (record) => {
					return "删除";
				}
			},
			{

				click: (field, record) => {
					config(record)
				},
				render: (record) => {
					return "配置";
				}
			}
		]
	}
])


const beforeUpload = () => {
	fileList.value = []
	return false;
}
const viewConfig = ref({
	visibleFlag: false,
	viewFlag: false,
	viewName: null,
	viewCode: null
})

const selectTree = (id) => {
	currentGroupId.value = id;
	refresh();
}
const refresh = () => {
	if (props.hiddenFlag) {
		return
	}
	tableRef.value.refresh(true)
}
const treeData = ref([])

const queryMenuTree = () => {
	// 获取菜单树并加入顶级
	const treeParam = {
		module: null
	}
	menuApi.menuTreeSelector(treeParam).then((res) => {
		treeData.value = [
			{
				id: 0,
				parentId: '-1',
				title: '顶级',
				children: res
			}
		]
	})
}

// 刷新缓存的菜单
const refreshCacheMenu = () => {
	nextTick(() => {
		userCenterApi.userLoginMenu().then((res) => {
			tool.data.set('MENU', res)
		})
	})
}

const offOnline = async (data) => {
	if (!data.publishFlag || data.publishFlag === 'OFFLINE') {
		await online({...data});
		data.publishFlag = 'ONLINE'
	} else if (data.publishFlag === 'ONLINE') {
		await offline({...data})
		data.publishFlag = 'OFFLINE'
	}

	if (props.operaCallback) {
		props.operaCallback('offline', 'view', {
			...data
		})
	}
}


const online = async (row) => {
	await viewConfigApi.online({
		id: row.id,
	});
	refreshCacheMenu();
	refresh()
}
const offline = async (row) => {
	await viewConfigApi.offline({
		id: row.id,
	});
	refreshCacheMenu();
	refresh()
}
const search = ref();

const tableRef = ref();
const queryList = async () => {
	return await viewConfigApi.list(
		{
			groupId: currentGroupId.value == 0 ? null : currentGroupId.value,
			productId: productId.value
		}
	);
}
onMounted(() => {
	productId.value = props.productId;
	if (!productId.value) {
		productId.value = proxy.$route.query.id
	}
	queryMenuTree();
})


const progress = (a) => {
	//this.uploadFile = a;
	let file = fileList.value[0].originFileObj
	let reader = new FileReader()
	// abort none 中断读取
	// readAsBinaryString file 将文件读取为二进制码，通常我们将它传送到后端，后端可以通过这段字符串存储文件
	// readAsDataURL file 将文件读取为 DataURL，一段以 data: 开头的字符串，这段字符串的实质就是 Data URL，Data URL是一种将小文件直接嵌入文档的方案。这里的小文件通常是指图像与 html 等格式的文件
	// readAsText file, [encoding] 将文件读取为文本，读取的结果即是这个文本文件中的内容
	reader.readAsDataURL(file)
	// onabort 中断时触发
	// onerror 出错时触发
	// onload 文件读取成功完成时触发
	// onloadend 读取完成触发，无论成功或失败
	// onloadstart 读取开始时触发
	// onprogress 读取中
	reader.onload = (e) => {
		// 读取文件内容
		const base64String = e.target.result;
		viewConfig.value.icon = base64String;
		// 接下来可对文件内容进行处理
	}
}

const add = () => {
	viewConfig.value = {};
	viewConfig.value.visibleFlag = true;
}

const save = async () => {
	viewConfig.value.groupId = currentGroupId.value == 0 ? null : currentGroupId.value;
	if (!viewConfig.value.groupId) {
		proxy.$Message.info('请选择分组');
		return;
	}
	viewConfig.value.productId = productId.value
	let id = await viewConfigApi.save(viewConfig.value);
	if (props.operaCallback) {
		props.operaCallback(viewConfig.value.id ? 'edit' : 'add', 'view', {
			...viewConfig.value,
			publishFlag: !viewConfig.publishFlag ? 'OFFLINE' : viewConfig.publishFlag,
			id: id
		})
	}
	viewConfig.value = {};
	refresh();

}
const remove = async (row) => {
	await viewConfigApi.removeById(row);
	refresh();
	if (props.operaCallback) {
		props.operaCallback('delete', 'view', {
			...row
		})
	}
}
const views = (row) => {
	viewConfig.value = row
	viewConfig.value.visibleFlag = true;
	viewConfig.value.viewFlag = true;

}
const edit = async (row) => {
	let data = await viewConfigApi.getById(row)
	viewConfig.value = data
	viewConfig.value.visibleFlag = true;
	viewConfig.value.viewFlag = false;
}
const router = useRouter()

const config = (row) => {
	router.push({
		path: '/lowcode/engine', query: {
			id: row.id
		}
	})
}


const show = (action, data) => {
	if (action == 'add') {
		currentGroupId.value = data.id;
		add()
	} else if (action == 'publish') {
		offOnline(data)
	} else if (action == 'delete') {
		remove(data);
	} else if (action == 'edit') {
		currentGroupId.value = data.groupId;
		edit(data);
	}
}

defineExpose({
	show
})
</script>

<style scoped></style>
